<template>
  <div class="task-upload-step">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>{{ userType === 'teacher' ? '教学任务' : '学习任务' }}</el-breadcrumb-item>
        <el-breadcrumb-item>创建{{ userType === 'teacher' ? '教学' : '学习' }}任务</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">创建{{ userType === 'teacher' ? '教学' : '学习' }}任务</h1>
    </div>

    <!-- 白色创建区域 -->
    <div class="creation-container">
      <!-- 步骤进度区域 - 第二步 -->
      <div class="steps-section">
        <el-steps :active="1" finish-status="success" align-center>
          <el-step title="填写任务信息" />
          <el-step title="上传试卷" />
        </el-steps>
      </div>

      <!-- 上传区域 -->
      <div class="upload-section">
        <!-- 选择上传方式标题 -->
        <div class="upload-title">选择上传方式</div>

        <!-- 上传方式选择 -->
        <div class="upload-methods">
          <!-- 拍照上传 -->
          <div class="upload-method" :class="{ active: uploadMethod === 'camera' }"
            @click="selectUploadMethod('camera')">
            <div class="method-icon camera-icon">
              <el-icon size="32">
                <Camera />
              </el-icon>
            </div>
            <div class="method-content">
              <h3>拍照上传</h3>
              <p>通过拍照扫描上传试卷</p>
            </div>
          </div>

          <!-- 本地文件上传 -->
          <div class="upload-method" :class="{ active: uploadMethod === 'file' }" @click="selectUploadMethod('file')">
            <div class="method-icon file-icon">
              <el-icon size="32">
                <Folder />
              </el-icon>
            </div>
            <div class="method-content">
              <h3>本地文件上传</h3>
              <p>支持上传试卷文件</p>
            </div>
          </div>
        </div>

        <!-- 上传试卷区域 -->
        <div class="upload-area-section">
          <div class="upload-area-title">上传试卷</div>

          <!-- 拍照上传区域 -->
          <div v-if="uploadMethod === 'camera'" class="camera-upload-area">
            <div class="camera-small-area" @click="openCameraCapture">
              <div class="camera-icon-section">
                <el-icon size="48" class="camera-icon">
                  <Camera />
                </el-icon>
              </div>
              <div class="camera-text-section">
                <h3>拍照上传</h3>
                <p>点击进入拍照模式</p>
              </div>
            </div>

            <!-- 已拍摄照片预览 -->
            <div v-if="capturedPhotos.length > 0" class="captured-photos">
              <div class="photos-title">已拍摄照片 ({{ capturedPhotos.length }}张)</div>
              <div class="photos-grid">
                <div v-for="(photo, index) in capturedPhotos" :key="photo" class="photo-item">
                  <div class="photo-preview">
                    <div class="photo-number">{{ index + 1 }}</div>
                    <div class="photo-content">
                      <!-- 模拟照片内容 -->
                      <div class="mock-paper">
                        <div class="paper-header">试卷{{ index + 1 }}</div>
                        <div class="paper-lines">
                          <div class="line"></div>
                          <div class="line"></div>
                          <div class="line"></div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <el-button type="danger" size="small" text @click="removePhoto(index)" class="remove-photo-btn">
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 文件上传区域 -->
          <div v-if="uploadMethod === 'file'" class="file-upload-area">
            <el-upload ref="uploadRef" :file-list="fileList" :before-upload="beforeUpload"
              :on-success="handleUploadSuccess" :on-remove="handleRemove" :on-change="handleFileChange" multiple drag
              accept=".jpg,.jpeg,.png,.pdf" :auto-upload="false" class="upload-dragger">
              <el-icon class="el-icon--upload" size="48">
                <UploadFilled />
              </el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 jpg/png/pdf 格式文件，单个文件大小不超过10MB
                </div>
              </template>
            </el-upload>

            <!-- 文件列表 -->
            <div v-if="fileList.length > 0" class="file-list">
              <div class="file-list-title">已选择文件：</div>
              <div v-for="file in fileList" :key="file.uid" class="file-item">
                <el-icon class="file-icon">
                  <Document />
                </el-icon>
                <span class="file-name">{{ file.name }}</span>
                <span class="file-size">{{ formatFileSize(file.size || 0) }}</span>
                <el-button type="danger" size="small" text @click="removeFile(file)" class="remove-btn">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="actions-section">
        <div class="actions-buttons">
          <el-button @click="handlePrevious" class="prev-btn">上一步</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="loading" :disabled="!canSubmit" class="submit-btn">
            提交
          </el-button>
        </div>
      </div>
    </div>

    <!-- 摄像头拍照组件 -->
    <CameraCapture v-if="showCameraCapture" :user-type="userType" @back="closeCameraCapture"
      @capture="handleCameraCapture" @import="handleCameraImport" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, Folder, UploadFilled, Document } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles } from 'element-plus'
import CameraCapture from '../Camera/CameraCapture.vue'

// 接口定义
interface CapturedPhoto {
  id: string
  thumbnail: string
  fullImage: string
  timestamp: number
  processed?: boolean
}

// Props
interface Props {
  userType: 'teacher' | 'student'
  taskData?: any
}

const props = withDefaults(defineProps<Props>(), {
  userType: 'teacher'
})

// Emits
const emit = defineEmits<{
  previous: []
  submit: [data: any]
}>()

// 响应式数据
const loading = ref(false)
const uploadMethod = ref<'camera' | 'file' | ''>('')
const cameraStarted = ref(false)
const capturedPhotos = ref<string[]>([])
const showCameraCapture = ref(false)
const uploadRef = ref()
const fileList = ref<UploadFile[]>([])

// 计算属性
const canSubmit = computed(() => {
  if (uploadMethod.value === 'camera') {
    return capturedPhotos.value.length > 0
  } else if (uploadMethod.value === 'file') {
    return fileList.value.length > 0
  }
  return false
})

// 方法
const selectUploadMethod = (method: 'camera' | 'file') => {
  uploadMethod.value = method
  // 清空之前的数据
  if (method === 'camera') {
    fileList.value = []
  } else {
    capturedPhotos.value = []
    cameraStarted.value = false
  }
}

const startCamera = () => {
  cameraStarted.value = true
  ElMessage.success('摄像头已启动')
}

const stopCamera = () => {
  cameraStarted.value = false
  ElMessage.info('摄像头已关闭')
}

const capturePhoto = () => {
  // 模拟拍照功能
  const photoId = `photo_${Date.now()}`
  capturedPhotos.value.push(photoId)
  ElMessage.success(`已拍摄第${capturedPhotos.value.length}张照片`)
}

const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return false // 阻止自动上传
}

const handleUploadSuccess = (response: any, file: UploadFile) => {
  ElMessage.success('文件上传成功')
}

const handleRemove = (file: UploadFile) => {
  ElMessage.info('文件已移除')
}

const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  fileList.value = files
}

const removeFile = (file: UploadFile) => {
  const index = fileList.value.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

const handlePrevious = () => {
  emit('previous')
}

const openCameraCapture = () => {
  showCameraCapture.value = true
}

const closeCameraCapture = () => {
  showCameraCapture.value = false
}

const handleCameraCapture = (photos: CapturedPhoto[]) => {
  capturedPhotos.value = photos.map(photo => photo.fullImage)
  showCameraCapture.value = false
  ElMessage.success(`已拍摄${photos.length}张照片`)
}

const handleCameraImport = () => {
  // 处理从摄像头界面导入文件
  showCameraCapture.value = false
  selectUploadMethod('file')
}

const removePhoto = (index: number) => {
  capturedPhotos.value.splice(index, 1)
  ElMessage.info('照片已删除')
}

const handleSubmit = async () => {
  if (!uploadMethod.value) {
    ElMessage.error('请选择上传方式')
    return
  }

  if (!canSubmit.value) {
    ElMessage.error(uploadMethod.value === 'camera' ? '请先拍摄照片' : '请先选择文件')
    return
  }

  loading.value = true

  try {
    // 模拟提交延迟
    await new Promise(resolve => setTimeout(resolve, 2000))

    const submitData = {
      taskData: props.taskData,
      uploadMethod: uploadMethod.value,
      files: uploadMethod.value === 'file' ? fileList.value : [],
      photos: uploadMethod.value === 'camera' ? capturedPhotos.value : []
    }

    emit('submit', submitData)
    ElMessage.success(`${props.userType === 'teacher' ? '教学' : '学习'}任务创建成功`)
  } catch (error) {
    ElMessage.error('创建失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.task-upload-step {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin-bottom: 16px;
}

:deep(.el-breadcrumb__inner) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-breadcrumb__inner.is-link) {
  color: #409EFF;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 白色创建区域 */
.creation-container {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 步骤进度区域 */
.steps-section {
  padding: 32px 48px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafbfc;
}

:deep(.el-steps) {
  max-width: 600px;
  margin: 0 auto;
}

:deep(.el-step__title) {
  font-size: 16px;
  font-weight: 500;
}

/* 上传区域 */
.upload-section {
  padding: 48px;
  min-height: 500px;
}

.upload-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 32px;
  text-align: center;
}

/* 上传方式选择 */
.upload-methods {
  display: flex;
  gap: 24px;
  margin-bottom: 48px;
  justify-content: center;
}

.upload-method {
  flex: 1;
  max-width: 280px;
  padding: 24px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 16px;
  background: #fafbfc;
}

.upload-method:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.upload-method.active {
  border-color: #409EFF;
  background: #f0f9ff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.method-icon {
  color: #409EFF;
  flex-shrink: 0;
}

.method-content h3 {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.method-content p {
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.4;
}

/* 上传试卷区域 */
.upload-area-section {
  max-width: 800px;
  margin: 0 auto;
}

.upload-area-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
}

/* 拍照上传区域 */
.camera-upload-area {
  text-align: center;
}

/* 拍照上传小区域 */
.camera-small-area {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 30px;
  border: 2px dashed #409EFF;
  border-radius: 12px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 24px;
}

.camera-small-area:hover {
  border-color: #1890ff;
  background: linear-gradient(135deg, #e6f7ff 0%, #d1f2ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.camera-icon-section {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 50%;
  flex-shrink: 0;
}

.camera-icon {
  color: #409EFF;
}

.camera-text-section {
  flex: 1;
  text-align: left;
}

.camera-text-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.camera-text-section p {
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.4;
}

/* 已拍摄照片预览 */
.captured-photos {
  margin-top: 32px;
}

.photos-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  text-align: left;
}

.photos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}

.photo-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.photo-preview {
  position: relative;
  width: 100px;
  height: 130px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.photo-preview:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.photo-number {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #409EFF;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.photo-content {
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 模拟试卷照片 */
.mock-paper {
  width: 90%;
  height: 90%;
  background: #fff;
  padding: 8px;
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
}

.paper-header {
  font-size: 10px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 6px;
  color: #333;
  line-height: 1.2;
}

.paper-lines {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 3px;
  justify-content: flex-start;
  padding-top: 4px;
}

.line {
  height: 1px;
  background: #ddd;
  width: 100%;
}

.remove-photo-btn {
  font-size: 12px;
  padding: 2px 8px;
}

.camera-container {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-placeholder {
  padding: 48px;
}

.camera-placeholder-icon {
  color: #c0c4cc;
  margin-bottom: 16px;
}

.camera-placeholder-text {
  font-size: 16px;
  color: #606266;
  margin: 0 0 24px 0;
}

.start-camera-btn {
  min-width: 120px;
}

.camera-preview {
  width: 100%;
  padding: 24px;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
}

.preview-placeholder {
  width: 400px;
  height: 300px;
  border: 2px dashed #409EFF;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f0f9ff;
  color: #409EFF;
}

.camera-controls {
  display: flex;
  gap: 16px;
}

.capture-btn {
  min-width: 100px;
}

/* 文件上传区域 */
.file-upload-area {
  max-width: 600px;
  margin: 0 auto;
}

.upload-dragger {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background: #f0f9ff;
}

:deep(.el-icon--upload) {
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409EFF;
  font-style: normal;
}

/* 文件列表 */
.file-list {
  margin-top: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.file-list-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
}

.file-item:last-child {
  border-bottom: none;
}

.file-icon {
  color: #409EFF;
  flex-shrink: 0;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #909399;
  flex-shrink: 0;
}

.remove-btn {
  flex-shrink: 0;
}

/* 操作按钮区域 */
.actions-section {
  padding: 24px 48px;
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.actions-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.prev-btn,
.submit-btn {
  min-width: 100px;
  height: 40px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .upload-section {
    padding: 32px;
  }

  .steps-section {
    padding: 24px 32px;
  }

  .actions-section {
    padding: 20px 32px;
  }
}

@media (max-width: 768px) {
  .task-upload-step {
    padding: 16px;
  }

  .upload-section {
    padding: 24px 16px;
  }

  .steps-section {
    padding: 20px 16px;
  }

  .actions-section {
    padding: 16px;
  }

  .upload-methods {
    flex-direction: column;
  }

  .upload-method {
    max-width: none;
  }

  .preview-placeholder {
    width: 100%;
    max-width: 350px;
  }

  .camera-controls {
    flex-direction: column;
    align-items: center;
  }
}
</style>